package pers.zero.jwt.spring;

import pers.zero.jwt.spring.config.JwtConfig;
import pers.zero.jwt.spring.interceptor.JwtTokenInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * <p><b>
 * 只能在一个地方配置拦截器。。。
 * </b></p>
 * <br/>
 * 创建时间: 9/3/2019 12:29 PM
 *
 * @author Zero
 */
@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {
    /**
     * jwt token 拦截器
     */
    @Autowired(required = false)
    private JwtTokenInterceptor jwtTokenInterceptor;

    @Autowired(required = false)
    private JwtConfig jwtConfig;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        if (jwtTokenInterceptor == null) {
            return;
        }

        // 如果 jwt 为禁用，直接不进行拦截器注册。
        if (!jwtConfig.enable) {
            return;
        }

        // 多个拦截器组成一个拦截器链
        // addPathPatterns 用于添加拦截规则
        // excludePathPatterns 用户排除拦截

        // jwt 拦截器
        registry.addInterceptor(jwtTokenInterceptor)
                .addPathPatterns(jwtConfig.getPath())
                .excludePathPatterns(
                        jwtConfig.getExcept()
                );

    }
}
